package site.isscloud.web.controller.project;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import site.isscloud.common.annotation.Log;
import site.isscloud.common.core.controller.BaseController;
import site.isscloud.common.core.domain.AjaxResult;
import site.isscloud.common.core.page.TableDataInfo;
import site.isscloud.common.enums.BusinessType;
import site.isscloud.common.utils.poi.ExcelUtil;
import site.isscloud.project.domain.PjAlarmEvent;
import site.isscloud.project.service.IPjAlarmEventService;

/**
 * 告警事件Controller
 */
@RestController
@RequestMapping("/project/event")
public class AlarmEventController extends BaseController
{
    @Autowired
    private IPjAlarmEventService alarmEventService;

    /**
     * 查询告警事件列表
     */
    @PreAuthorize("@ss.hasPermi('project:event:list')")
    @GetMapping("/list")
    public TableDataInfo list(PjAlarmEvent pjAlarmEvent, HttpServletRequest request)
    {
        // 设置时间范围参数到 params 中
        Map<String, Object> params = pjAlarmEvent.getParams();
        if (params == null) {
            params = new HashMap<>();
            pjAlarmEvent.setParams(params);
        }

        // 直接从请求参数中获取
        String beginTime = request.getParameter("params[beginTime]");
        String endTime = request.getParameter("params[endTime]");

        if (beginTime != null && !beginTime.trim().isEmpty()) {
            params.put("beginTime", beginTime);
        }
        if (endTime != null && !endTime.trim().isEmpty()) {
            params.put("endTime", endTime);
        }

        // 获取米标范围参数
        String minMeterMark = request.getParameter("minMeterMark");
        String maxMeterMark = request.getParameter("maxMeterMark");
        if (minMeterMark != null && !minMeterMark.trim().isEmpty()) {
            params.put("minMeterMark", Integer.parseInt(minMeterMark));
        }
        if (maxMeterMark != null && !maxMeterMark.trim().isEmpty()) {
            params.put("maxMeterMark", Integer.parseInt(maxMeterMark));
        }

        // 获取断纤位置范围参数
        String minFiberBreakPosition = request.getParameter("minFiberBreakPosition");
        String maxFiberBreakPosition = request.getParameter("maxFiberBreakPosition");
        if (minFiberBreakPosition != null && !minFiberBreakPosition.trim().isEmpty()) {
            params.put("minFiberBreakPosition", Integer.parseInt(minFiberBreakPosition));
        }
        if (maxFiberBreakPosition != null && !maxFiberBreakPosition.trim().isEmpty()) {
            params.put("maxFiberBreakPosition", Integer.parseInt(maxFiberBreakPosition));
        }

        startPage();
        List<PjAlarmEvent> list = alarmEventService.selectPjAlarmEventList(pjAlarmEvent);
        return getDataTable(list);
    }

    /**
     * 处理告警事件（标记为已处理）
     */
    @PreAuthorize("@ss.hasPermi('project:event:handle')")
    @Log(title = "告警事件", businessType = BusinessType.UPDATE)
    @PostMapping("/handle")
    public AjaxResult handle(@RequestBody Map<String, Object> params)
    {
        Long eventId = Long.valueOf(params.get("eventId").toString());
        String handledResult = (String) params.get("handledResult");
        String handledBy = (String) params.get("handledBy");
        // 如果没有传递处理时间，则设置为当前时间
        Date handledTime = (Date) params.get("handledTime");
        if (handledTime == null) {
            handledTime = new Date();
        }
        int result = alarmEventService.handleEvent(eventId, handledResult, handledBy, handledTime);
        return toAjax(result);
    }

    /**
     * 批量处理告警事件
     */
    @PreAuthorize("@ss.hasPermi('project:event:handle')")
    @Log(title = "告警事件", businessType = BusinessType.UPDATE)
    @PostMapping("/handleBatch")
    public AjaxResult handleBatch(@RequestBody Map<String, Object> params) {
        try {
            @SuppressWarnings("unchecked")
            List<Object> eventIdObjects = (List<Object>) params.get("eventIds");
            String handledResult = (String) params.get("handledResult");
            String handledBy = (String) params.get("handledBy");
            Date handledTime = (Date) params.get("handledTime");
            if (handledTime == null) {
                handledTime = new Date();
            }

            if (eventIdObjects == null || eventIdObjects.isEmpty()) {
                return error("请选择要处理的事件");
            }

            // 转换为Long类型
            List<Long> eventIds = eventIdObjects.stream()
                    .map(obj -> {
                        if (obj instanceof Integer) {
                            return ((Integer) obj).longValue();
                        } else if (obj instanceof Long) {
                            return (Long) obj;
                        } else {
                            return Long.valueOf(obj.toString());
                        }
                    })
                    .collect(Collectors.toList());

            int total = 0;
            for (Long eventId : eventIds) {
                int result = alarmEventService.handleEvent(eventId, handledResult, handledBy, handledTime);
                total += result;
            }

            return success("成功处理 " + total + " 个事件");
        } catch (Exception e) {
//            log.error("批量处理事件失败", e);
            return error("批量处理事件失败: " + e.getMessage());
        }
    }

    /**
     * 导出告警事件列表
     */
    @PreAuthorize("@ss.hasPermi('project:event:export')")
    @Log(title = "告警事件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PjAlarmEvent pjAlarmEvent)
    {
        List<PjAlarmEvent> list = alarmEventService.selectPjAlarmEventList(pjAlarmEvent);
        ExcelUtil<PjAlarmEvent> util = new ExcelUtil<PjAlarmEvent>(PjAlarmEvent.class);
        util.exportExcel(response, list, "告警事件数据");
    }

    /**
     * 获取告警事件详细信息
     */
    @PreAuthorize("@ss.hasPermi('project:event:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(Long id)
    {
        return success(alarmEventService.selectPjAlarmEventById(id));
    }
}